/*
 * This file is part of SSHTTPD.
 *
 * SSHTTPD is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SSHTTPD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @file
 * Wraps around the BSD socket system providing socket init routines and 
 * higher level functions for reading/writing data to it.
 */

/* Application level includes. */
#include "include/socket.h"
#include "include/request.h"
#include "include/utils.h"
#include "include/file.h"
#include "include/main.h"

/* System level includes. */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/types.h>
#include <arpa/inet.h>

/** Maxiumum clients the operating system will queue. */
#define MAXCLIENT 1024 

int init_socket(struct sockaddr_in *addr, int size, int port) {
	int sd;
	
	/* Set some socket info. */
	addr->sin_family = AF_INET;
	addr->sin_port = htons(port);
	addr->sin_addr.s_addr = INADDR_ANY;
	
	/* Ask the OS for a socket then prep it for connections. */
	sd = socket(PF_INET, SOCK_STREAM, 0);
	
	if(sd == -1) {
		event(EPROB, "socket() in init_socket()");
		return -1;
	}
	if(bind(sd, (struct sockaddr*)addr, size) != 0) {
		event(EPROB, "bind() in init_socket()");
		return -1;
	}
	if(listen(sd, MAXCLIENT) != 0) {
		event(EPROB, "listen() in init_socket()");
		return -1;
	}
	
	return sd;
}

#define RECBUFFMAX 1024 /** < Size for the request buffer. */

char *readrequest(int ud) { 
	int rgot = 0;
	int offset = 0;
	char *buffer;
	
	/* Allocate some space for the request header. */
	buffer = malloc(RECBUFFMAX);
	if(buffer == NULL) { 
		event(EPROB, "malloc() in readrequest()");
		return NULL;
	}
	
	/* Wait till we have all the data by reading from the recv buffer untill
	 * \r\n\r\n is recieved. */ 
	while(1) {
		rgot = recv(ud, buffer+offset, (RECBUFFMAX-offset)-1, 0);
		if(rgot <= 0) {
			event(EPROB, "recv error");
			free(buffer);
			return NULL;
		}
		
		/* Using an offset to keep our place in the buffer so nothing
		 * gets overridden. */
		offset += rgot;
		/* Append a null char to the end incase there isnt one and 
		 * string aware functions fail, this gets overwritten next 
		 * iteration unless it is the last one. */
		buffer[offset] = '\0';
		
		/*Look for \r\n\r\n in the recieve buffer, if it is found
		 * we have found the end of the data we need. */
		if(strstr(buffer, "\r\n\r\n") != NULL) 
			break;
	} 
	event(ELOG, "recieved %d bytes", rgot); 
	return buffer;
}
